let crawling = false;
let images = new Set();
let articles = new Set();
let currentPage = 1;
const imagesPerPage = 12;
let autoDownload = false;
let targetImages = 2000;
let targetPages = 10;

// 模板管理相关变量
let currentConfig = null;
let editingTemplate = null;
let currentDomain = '';
let currentTemplate = null;

// 验证URL是否为图片
function isImageUrl(url) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  const urlLower = url.toLowerCase();
  return imageExtensions.some(ext => urlLower.includes(ext));
}

// 重置所有数据
function resetAllData() {
  if (confirm('确定要清除所有已爬取的数据吗？')) {
    images.clear();
    articles.clear();
    chrome.storage.local.remove(['images', 'articles']);
    updateStatus();
    const downloadStatus = document.getElementById('downloadStatus');
    if (downloadStatus) {
      downloadStatus.remove();
    }
    document.getElementById('currentPage').textContent = '当前页码：0';
    document.getElementById('imageList').style.display = 'none';
    document.getElementById('pagination').innerHTML = '';
  }
}

// 初始化事件监听器
function initializeEventListeners() {
  const buttons = {
    'startCrawl': () => startCrawling(false),
    'stopCrawl': stopCrawling,
    'viewImages': showImages,
    'downloadImages': downloadAllImages,
    'exportExcel': exportToExcelFile,
    'crawlAndDownload': () => startCrawling(true),
    'resetAll': resetAllData,
    'manageTemplates': async () => {
      if (!currentConfig) {
        currentConfig = await loadConfig();
      }
      showTemplateList();
      document.getElementById('templateDialog').style.display = 'flex';
    },
    'closeDialog': () => {
      document.getElementById('templateDialog').style.display = 'none';
    },
    'cancelTemplate': () => {
      document.getElementById('editTemplateDialog').style.display = 'none';
    },
    'addTemplate': () => {
      editingTemplate = null;
      document.getElementById('templateDomain').value = '';
      document.getElementById('templatePageUrl').value = '';
      document.getElementById('templateListSelector').value = '';
      document.getElementById('templateImageSelector').value = '';
      document.getElementById('editTemplateDialog').style.display = 'flex';
    },
    'saveTemplates': async () => {
      try {
        if (!currentConfig || !currentConfig.selectors) {
          throw new Error('配置数据无效');
        }
        await saveConfig();
        document.getElementById('templateDialog').style.display = 'none';
        // 重新加载当前域名的模板
        if (currentDomain && currentConfig.selectors[currentDomain]) {
          currentTemplate = currentConfig.selectors[currentDomain];
          updateTemplateStatus();
        }
      } catch (error) {
        console.error('保存配置失败:', error);
        alert('保存配置失败，请重试！');
      }
    },
    'saveTemplate': () => {
      saveTemplate();
    }
  };
  
  Object.entries(buttons).forEach(([id, handler]) => {
    const button = document.getElementById(id);
    if (button) {
      // 移除现有的事件监听器
      const newButton = button.cloneNode(true);
      button.parentNode.replaceChild(newButton, button);
      // 添加新的事件监听器
      newButton.addEventListener('click', handler);
    }
  });

  // 监听输入框变化
  const targetImagesInput = document.getElementById('targetImages');
  if (targetImagesInput) {
    const newInput = targetImagesInput.cloneNode(true);
    targetImagesInput.parentNode.replaceChild(newInput, targetImagesInput);
    newInput.addEventListener('change', (e) => {
      targetImages = parseInt(e.target.value) || 5000;
    });
  }

  const targetPagesInput = document.getElementById('targetPages');
  if (targetPagesInput) {
    const newInput = targetPagesInput.cloneNode(true);
    targetPagesInput.parentNode.replaceChild(newInput, targetPagesInput);
    newInput.addEventListener('change', (e) => {
      targetPages = parseInt(e.target.value) || 50;
    });
  }
}

// 初始化时从storage加载数据
async function initializeData() {
  // 等待面板DOM加载完成
  if (!document.getElementById('templateStatus')) {
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  try {
    const result = await chrome.storage.local.get(['images', 'articles', 'configOverride']);
    
    if (result.images) {
      images = new Set(result.images);
    }
    if (result.articles) {
      articles = new Set(result.articles);
    }
    updateStatus();
    
    // 加载配置
    currentConfig = await loadConfig();
    if (result.configOverride) {
      Object.assign(currentConfig, result.configOverride);
    }
    
    // 获取当前标签页的域名
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tab && tab.url) {
      const url = new URL(tab.url);
      currentDomain = url.hostname;
      
      // 查找匹配的模板
      if (currentConfig.selectors[currentDomain]) {
        currentTemplate = currentConfig.selectors[currentDomain];
        updateTemplateStatus();
      }
    }
    
    // 初始化事件监听器
    initializeEventListeners();
    
  } catch (error) {
    console.error('初始化数据失败:', error);
    // 使用默认值
    images = new Set();
    articles = new Set();
    currentConfig = await loadConfig();
    updateStatus();
    // 即使出错也要初始化事件监听器
    initializeEventListeners();
  }
}

// 加载配置文件
async function loadConfig() {
  try {
    const response = await fetch(chrome.runtime.getURL('config.json'));
    if (!response.ok) {
      throw new Error('加载配置文件失败');
    }
    const config = await response.json();
    if (!config || !config.selectors) {
      throw new Error('配置文件格式无效');
    }
    return config;
  } catch (error) {
    console.error('加载配置失败:', error);
    // 返回一个基本的配置结构
    return {
      selectors: {},
      defaultSelectors: {
        listSelector: "",
        imageSelector: ""
      }
    };
  }
}

// 保存配置文件
async function saveConfig() {
  try {
    if (!currentConfig || !currentConfig.selectors) {
      throw new Error('当前配置无效');
    }
    await chrome.storage.local.set({ configOverride: currentConfig });
    console.log('配置已保存:', currentConfig);
  } catch (error) {
    console.error('保存配置失败:', error);
    throw error;
  }
}

// 显示模板列表
function showTemplateList() {
  const templateList = document.getElementById('templateList');
  templateList.innerHTML = '';
  
  Object.entries(currentConfig.selectors).forEach(([domain, config]) => {
    const templateItem = document.createElement('div');
    templateItem.className = 'template-item';
    templateItem.innerHTML = `
      <div><strong>域名：</strong>${domain}</div>
      <div><strong>页面URL：</strong>${config.pageUrl}</div>
      <div><strong>列表选择器：</strong>${config.listSelector}</div>
      <div><strong>图片选择器：</strong>${config.imageSelector}</div>
      <div class="template-actions">
        <button class="edit-btn" data-domain="${domain}">编辑</button>
        <button class="delete-btn" data-domain="${domain}">删除</button>
      </div>
    `;
    const editBtn = templateItem.querySelector('.edit-btn');
    const deleteBtn = templateItem.querySelector('.delete-btn');
    editBtn.addEventListener('click', () => editTemplate(domain));
    deleteBtn.addEventListener('click', () => deleteTemplate(domain));
    templateList.appendChild(templateItem);
  });
}

// 编辑模板
function editTemplate(domain) {
  console.log('编辑模板:', domain);
  editingTemplate = domain;
  const template = currentConfig.selectors[domain];
  
  document.getElementById('templateDomain').value = domain;
  document.getElementById('templatePageUrl').value = template.pageUrl;
  document.getElementById('templateListSelector').value = template.listSelector;
  document.getElementById('templateImageSelector').value = template.imageSelector;
  
  document.getElementById('editTemplateDialog').style.display = 'flex';
}

// 删除模板
function deleteTemplate(domain) {
  if (confirm(`确定要删除 ${domain} 的模板吗？`)) {
    delete currentConfig.selectors[domain];
    showTemplateList();
  }
}

// 保存模板
function saveTemplate() {
  const domain = document.getElementById('templateDomain').value;
  if (!domain) {
    alert('域名不能为空！');
    return;
  }
  
  const template = {
    pageUrl: document.getElementById('templatePageUrl').value,
    listSelector: document.getElementById('templateListSelector').value,
    imageSelector: document.getElementById('templateImageSelector').value
  };
  
  // 验证必填字段
  if (!template.pageUrl || !template.listSelector || !template.imageSelector) {
    alert('所有字段都必须填写！');
    return;
  }
  
  currentConfig.selectors[domain] = template;
  document.getElementById('editTemplateDialog').style.display = 'none';
  showTemplateList();
  
  // 如果是当前域名的模板，更新状态
  if (currentDomain === domain) {
    currentTemplate = template;
    updateTemplateStatus();
  }
}

// 更新模板状态显示
function updateTemplateStatus() {
  const templateStatus = document.getElementById('templateStatus');
  if (currentTemplate) {
    templateStatus.innerHTML = `
      <div><strong>当前域名：</strong>${currentDomain}</div>
      <div><strong>使用模板：</strong></div>
      <div>页面URL：${currentTemplate.pageUrl}</div>
      <div>列表选择器：${currentTemplate.listSelector}</div>
      <div>图片选择器：${currentTemplate.imageSelector}</div>
    `;
    templateStatus.style.display = 'block';
    // 启用爬取按钮
    document.getElementById('startCrawl').disabled = false;
    document.getElementById('crawlAndDownload').disabled = false;
  } else {
    templateStatus.innerHTML = `
      <div><strong>当前域名：</strong>${currentDomain}</div>
      <div class="warning">未找到匹配的模板配置！</div>
    `;
    templateStatus.style.display = 'block';
    // 禁用爬取按钮
    document.getElementById('startCrawl').disabled = true;
    document.getElementById('crawlAndDownload').disabled = true;
  }
}

// 修改startCrawling函数
async function startCrawling(withDownload) {
  if (crawling) return;
  if (!currentTemplate) {
    alert('请先选择或配置模板！');
    return;
  }
  crawling = true;
  autoDownload = withDownload;
  
  try {
    console.log('开始爬取');
    // 使用当前选择的模板
    const config = {
      selectors: {
        [currentDomain]: currentTemplate
      }
    };
    
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    console.log('当前标签页:', tab);
    
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ['content.js']
    });
    
    console.log('发送startCrawl消息');
    chrome.tabs.sendMessage(tab.id, {
      type: 'startCrawl',
      config: config,
      existingArticles: Array.from(articles),
      targetImages: targetImages,
      targetPages: targetPages
    });
  } catch (error) {
    console.error('启动爬虫错误:', error);
    alert('启动爬虫失败: ' + error.message);
  }
}

function stopCrawling() {
  crawling = false;
}

function updateStatus() {
  document.getElementById('articleStatus').textContent = `已爬取网页：${articles.size} 个`;
  document.getElementById('imageStatus').textContent = `已爬取图片：${images.size} 张`;
}


function showImages() {
  const imageList = document.getElementById('imageList');
  const paginationDiv = document.getElementById('pagination');
  imageList.style.display = 'block';
  
  const imageArray = Array.from(images);
  const startIndex = (currentPage - 1) * imagesPerPage;
  const endIndex = startIndex + imagesPerPage;
  const pageImages = imageArray.slice(startIndex, endIndex);
  
  imageList.innerHTML = pageImages.map(src => 
    `<img src="${src}" alt="爬取的图片">`
  ).join('');
  
  const totalPages = Math.ceil(imageArray.length / imagesPerPage);
  paginationDiv.innerHTML = `
    第${currentPage}页/共${totalPages}页
    <button onclick="changePage(-1)" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>
    <button onclick="changePage(1)" ${currentPage === totalPages ? 'disabled' : ''}>下一页</button>
  `;
}

function changePage(delta) {
  currentPage += delta;
  showImages();
}

async function downloadAllImages() {
  const imageArray = Array.from(images);
  const totalImages = imageArray.length;
  
  if (totalImages === 0) {
    alert('没有可下载的图片！');
    return;
  }

  // 过滤掉已下载的图片
  const downloadedImages = new Set();
  const statusDiv = document.getElementById('downloadStatus') || createDownloadStatus();
  let downloadedCount = 0;

  const batchSize = 10;
  for (let i = 0; i < totalImages; i += batchSize) {
    const batch = imageArray.slice(i, i + batchSize);
    const downloadPromises = batch.map((url, index) => {
      if (downloadedImages.has(url)) {
        console.log('图片已下载，跳过:', url);
        return Promise.resolve();
      }
      downloadedImages.add(url);
      return downloadImage(url, i + index + 1);
    });
    
    try {
      await Promise.all(downloadPromises);
      downloadedCount += batch.filter(url => downloadedImages.has(url)).length;
      updateDownloadProgress(downloadedCount, totalImages);
    } catch (error) {
      console.error('下载出错:', error);
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

// 下载单张图片
async function downloadImage(url, index) {
  // 验证URL是否为图片
  if (!isImageUrl(url)) {
    console.log('跳过非图片URL:', url);
    return;
  }
  
  try {
    // 获取图片的实际格式
    const response = await fetch(url);
    const contentType = response.headers.get('content-type');
    
    // 验证content-type是否为图片
    if (!contentType || !contentType.startsWith('image/')) {
      console.log('跳过非图片内容:', url);
      return;
    }
    
    const blob = await response.blob();
    
    // 根据content-type确定文件扩展名
    let extension = 'jpg'; // 默认扩展名
    if (contentType) {
      if (contentType.includes('png')) {
        extension = 'png';
      } else if (contentType.includes('gif')) {
        extension = 'gif';
      } else if (contentType.includes('jpeg') || contentType.includes('jpg')) {
        extension = 'jpg';
      } else if (contentType.includes('webp')) {
        extension = 'webp';
      }
    }

    // 创建blob URL
    const blobUrl = URL.createObjectURL(blob);
    
    // 使用chrome.downloads API下载
    await chrome.downloads.download({
      url: blobUrl,
      filename: `lofter_image_${String(index).padStart(3, '0')}.${extension}`,
      saveAs: false
    });

    // 清理blob URL
    URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.error(`下载图片失败 ${url}:`, error);
  }
}

// 创建下载进度显示
function createDownloadStatus() {
  const statusDiv = document.createElement('div');
  statusDiv.id = 'downloadStatus';
  statusDiv.className = 'download-status';
  document.querySelector('.status-info').appendChild(statusDiv);
  return statusDiv;
}

// 更新下载进度
function updateDownloadProgress(current, total) {
  const statusDiv = document.getElementById('downloadStatus');
  if (statusDiv) {
    statusDiv.textContent = `下载进度: ${current}/${total}`;
  }
}

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  try {
    if (message.type === 'newImage') {
      // 验证是否为图片URL
      if (!isImageUrl(message.url)) {
        console.log('跳过非图片URL:', message.url);
        sendResponse({ success: false, reason: 'not_image' });
        return;
      }
      
      // 如果图片已存在，直接跳过
      if (images.has(message.url)) {
        console.log('图片已存在，跳过:', message.url);
        sendResponse({ success: false, reason: 'duplicate' });
        return;
      }
      
      // 验证图片URL的有效性
      fetch(message.url)
        .then(response => {
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.startsWith('image/')) {
            images.add(message.url);
            chrome.storage.local.set({ images: Array.from(images) });
            updateStatus();
            
            // 如果是新图片且开启了自动下载，则下载
            if (autoDownload) {
              downloadImage(message.url, images.size);
            }
            
            // 检查是否达到目标图片数量
            if (images.size >= targetImages) {
              stopCrawling();
            }
            sendResponse({ success: true });
          } else {
            console.log('跳过非图片内容:', message.url);
            sendResponse({ success: false, reason: 'invalid_content_type' });
          }
        })
        .catch(error => {
          console.error('验证图片失败:', error);
          sendResponse({ success: false, error: error.message });
        });
      return true; // 保持消息通道打开
    } else if (message.type === 'newArticle') {
      articles.add(message.url);
      chrome.storage.local.set({ articles: Array.from(articles) });
      updateStatus();
      sendResponse({ success: true });
    } else if (message.type === 'updateCurrentPage') {
      document.getElementById('currentPage').textContent = `当前页码：${message.page}`;
      // 检查是否达到目标页数
      if (message.page >= targetPages) {
        stopCrawling();
      }
      sendResponse({ success: true });
    }
  } catch (error) {
    console.error('处理消息出错:', error);
    sendResponse({ success: false, error: error.message });
  }
  return true; // 保持消息通道打开
});

// 导出Excel文件
function exportToExcelFile() {
  if (images.size === 0) {
    alert('没有可导出的图片数据！');
    return;
  }
  exportToExcel(images);
}

// 将所有需要的函数暴露到全局作用域
window.startCrawling = startCrawling;
window.stopCrawling = stopCrawling;
window.showImages = showImages;
window.downloadAllImages = downloadAllImages;
window.exportToExcelFile = exportToExcelFile;
window.resetAllData = resetAllData;
window.showTemplateList = showTemplateList;
window.loadConfig = loadConfig;
window.currentConfig = currentConfig;
window.initializeData = initializeData;
window.initializeEventListeners = initializeEventListeners; 